﻿using System;
using System.IO;

namespace KamRemakeRemake.GameObjects.MapObjects {
    public static class MapParser {
        private const string PATHTOMAPS = @"\Content\Maps\";

        public static Map LoadMap(string mapName) {
            // Read the map file
            string pathToMap = GetMapPath(mapName);
            string mapFileContent = File.ReadAllText(pathToMap);

            // Initialize the tiles array
            string[] rows = mapFileContent.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            int columnLength = rows[0].Split(',').Length;
            Tile[,] tiles = new Tile[rows.Length, columnLength];

            // Loop through all the lines in the mapfile
            for (int rowIndex = 0; rowIndex < rows.Length; rowIndex++) {
                // Loop through all the command seperated values of each line
                string[] columns = rows[rowIndex].Split(',');
                for (int colIndex = 0; colIndex < columns.Length; colIndex++) {
                    // Add the new tile to our array
                    int tileType = int.Parse(columns[colIndex]);
                    tiles[rowIndex, colIndex] = new Tile((TileType)tileType, rowIndex, colIndex);
                }
            }

            return new Map(tiles);
        }

        private static string GetMapPath(string mapName) {
            return String.Concat(AppDomain.CurrentDomain.BaseDirectory, 
                                 PATHTOMAPS,
                                 mapName, 
                                 ".map");
        }
    }
}
